package com.funtonow.jqdk.fkcs.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.adapter.LoanListAdapter;
import com.funtonow.jqdk.base.BaseActivity;
import com.funtonow.jqdk.base.BaseBean;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.base.SqjAppliaction;
import com.funtonow.jqdk.base.UrlUtils;
import com.funtonow.jqdk.bean.DkNumBean;
import com.funtonow.jqdk.bean.GameThirdInfoListBean;
import com.funtonow.jqdk.bean.LoanInfoBean;
import com.funtonow.jqdk.bean.UserInfoBean;
import com.funtonow.jqdk.ui.VipActivity;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.LogUtil;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.StatisticsUtils;
import com.funtonow.jqdk.utils.ToastUtils;
import com.funtonow.jqdk.widget.ProgressDialogUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

import static com.funtonow.jqdk.base.Constants.OWN_APP_ID;
import static com.funtonow.jqdk.base.UrlUtils.ED_JS;
import static com.funtonow.jqdk.base.UrlUtils.TUI_JIAN;

/**
 * @author Jiajien
 * @date 2019/6/25
 * 审核结果
 */
public class DkFailActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.tv_countdown)
    TextView tvCountDown;
    @BindView(R.id.rlv_recommend)
    RecyclerView rlvRecommend;
    @BindView(R.id.ll_recommend)
    LinearLayout llRecommend;
    @BindView(R.id.tv_audit_result)
    TextView tvAuditResult;
    @BindView(R.id.tv_audit_result1)
    TextView tvAuditResult1;
    @BindView(R.id.ll_fk_ing)
    LinearLayout llFkIng;
    @BindView(R.id.ll_fk_fail)
    LinearLayout llFkFail;

    private CountDownTimer countDownTimer;
    private LoanListAdapter recommendAdapter;
    private List<GameThirdInfoListBean> gameThirdInfoListBeans = new ArrayList<>();
    private UserInfoBean userInfoBean;
    private Intent intent;

    @Override
    public int getLayoutRes() {
        return R.layout.activity_fk_fail;
    }

    @Override
    public void onCreateActivity(@Nullable Bundle savedInstanceState) {
        initToolbar(getResources().getString(R.string.title_user_info));
        initRecyclerView(rlvRecommend);
        recommendAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (SPUtil.getUserInfo() != null && recommendAdapter.getItem(position).getVipfw() == 1
                        && SPUtil.getUserInfo().getHasVip() == 0) {
                    ToastUtils.show("该产品仅限会员申请");
                    startActivity(new Intent(DkFailActivity.this, VipActivity.class));
                } else {
                    GameThirdInfoListBean gameThirdInfoListBean = recommendAdapter.getItem(position);
                    assert gameThirdInfoListBean != null;
                    StatisticsUtils.clickUrl(gameThirdInfoListBean);
                    StatisticsUtils.intentWebView(DkFailActivity.this,
                            gameThirdInfoListBean.getUrl(), gameThirdInfoListBean.getName(),
                            gameThirdInfoListBean.getChanpinid());
                }
            }
        });
        getAppId();
        countDownTime(30);
    }

    private void initRecyclerView(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        //设置增加或删除条目的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recommendAdapter = new LoanListAdapter();
        recyclerView.setAdapter(recommendAdapter);
    }

    /**
     * 推荐列表
     */
    private void recommend() {
        userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        param.put("showappid", Constants.DATA_APP_ID);
        HttpUtil.getInstance().postDataAsynToNet(TUI_JIAN, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                JSONObject jsonObject = JSON.parseObject(SqjAppliaction.loanInfoBean.getCpMap());
                if (JSON.parseObject(jsonString).getInteger("errnum") != -1) {
                    String jsonArray = JSON.parseObject(jsonString).getJSONArray("data").toJSONString();
                    List<String> stringList = JSON.parseArray(jsonArray, String.class);
                    for (String s : stringList) {
                        for (LoanInfoBean.HeziInfoListBean heziInfoListBean : SqjAppliaction.loanInfoBean.getHeziInfoList()) {
                            if (s.equals(heziInfoListBean.getGdid())) {
                                for (LoanInfoBean.GdlistBean gdlistBean : SqjAppliaction.loanInfoBean.getGdlist()) {
                                    if (s.equals(gdlistBean.getGdid())) {
                                        GameThirdInfoListBean gameThirdInfoListBean = JSON.parseObject(jsonObject.getJSONObject(gdlistBean.getChanpinid()).toJSONString(), GameThirdInfoListBean.class);
                                        gameThirdInfoListBean.setVipfw(gdlistBean.getVipfw());
                                        gameThirdInfoListBean.setUrl(gdlistBean.getUrl());
                                        gameThirdInfoListBean.setHeziId(heziInfoListBean.getType());
                                        gameThirdInfoListBean.setIndex(heziInfoListBean.getInde());
                                        gameThirdInfoListBean.setGdId(s);
                                        gameThirdInfoListBeans.add(gameThirdInfoListBean);
                                    }
                                }
                            }
                        }
                    }
                    if (gameThirdInfoListBeans.size() > 0) {
                        recommendAdapter.setNewData(gameThirdInfoListBeans);
                        llRecommend.setVisibility(View.VISIBLE);
                    } else {
                        llRecommend.setVisibility(View.GONE);
                    }
                    StatisticsUtils.baoGuang(Constants.HEZI_ID_25);
                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    public void countDownTime(int time) {
        countDownTimer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // TODO Auto-generated method stub
                tvCountDown.setText(String.format(Locale.getDefault(), "%ds", millisUntilFinished / 1000));

            }

            @Override
            public void onFinish() {
                getMoneyNum();
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    /**
     * 获取数据appId
     */
    private void getAppId() {
        HttpUtil.getInstance().getDataAsynFromNet(UrlUtils.GET_APPID, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                Constants.DATA_APP_ID = JSON.parseObject(jsonString).getString("appId");
                recommend();
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    /**
     * 得到可贷款金额
     */
    private void getMoneyNum() {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        HttpUtil.getInstance().postDataAsynToNet(ED_JS, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                LogUtil.i(jsonString + " *********  ");
                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                if (baseBean.errnum > -1) {
                    DkNumBean dkNumBean = JSON.parseObject(baseBean.data, DkNumBean.class);
                    if (dkNumBean.getKtxed() > 0) {
                        intent = new Intent(DkFailActivity.this, DkSuccessActivity.class);
                        intent.putExtra("dkInfo", baseBean.data);
                        startActivity(intent);
                    } else {
                        llFkIng.setVisibility(View.GONE);
                        llFkFail.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    @OnClick({R.id.iv_black_query})
    @Override
    public void onClick(View v) {
        checkOcr();
    }

    private void checkOcr() {
        ProgressDialogUtil.startProgressDialog(this);
        Map<String, String> param = new HashMap<>();
        param.put("appid", OWN_APP_ID);
        param.put("openid", userInfoBean.getOpenid());
        param.put("token", userInfoBean.getToken());
        HttpUtil.getInstance().postDataAsynToNet(UrlUtils.OCR, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                ProgressDialogUtil.stopProgressDialog();
                JSONObject jsonObject = JSON.parseObject(jsonString);
                switch (jsonObject.getInteger("errnum")) {
                    case 0:
                        StatisticsUtils.intentWebView(DkFailActivity.this,
                                jsonObject.getString("data"), "黑名单检测", "");
                        break;
                    case -2:
                        intent = new Intent(DkFailActivity.this, CardActivity.class);
                        intent.putExtra("isBlack", true);
                        startActivity(intent);
                        break;
                    default:
                        ToastUtils.show(jsonObject.getString("data"));
                        break;
                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

}
